package com.nulldev.util.concurrency.threadIt.v4.deadlocks;

import java.lang.management.ThreadInfo;
import java.util.concurrent.TimeUnit;

public class GlobalDeadlockDetector {

	private static DeadlockDetector detector = null;

	static {
		if (detector == null) {
			detector = new DeadlockDetector(5, TimeUnit.SECONDS);
			detector.start();
			detector.submitHandler(new IDeadlockEvent() {

				@Override
				public void deadlock(final DeadlockMeta metadata) {
					System.err.println("[threadIt! v4] A deadlock has been detected.");
					for (final ThreadInfo tf : metadata.getThreads()) {
						if (tf == null) {
							continue;
						}
						for (Thread thread : Thread.getAllStackTraces().keySet()) {
							if (thread.getId() == tf.getThreadId()) {
								System.err.println("\t" + tf.toString().trim());
								for (StackTraceElement ste : thread.getStackTrace()) {
									System.err.println("\t\t" + ste.toString().trim());
								}
							}
						}
					}
				}
			});
		}
	}

	public static void tryToInitDeadlockDetector() {
	}
}
